<template>
  <div class="p-4">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-form inline>
          <el-form-item>
            <el-button
              icon="el-icon-plus"
              type="success"
              @click="deBounceWrap(handleAdd)"
            >新增
            </el-button
            >
            <!-- <el-button type="danger" icon="el-icon-delete" @click="deBounceWrap(handleDelAll)">删除</el-button> -->
          </el-form-item>
        </el-form>
        <div class="flex mt-3">
          <el-select
            v-model="listQuery.relation_type"
            clearable
            placeholder="请选择关系类别"
            style="width: 17%"
          >
            <el-option
              v-for="item in styleLabelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              clearable
            >
            </el-option>
          </el-select>

          <el-date-picker
            v-model="listQuery.add_time"
            class="ml-4"
            clearable
            format="yyyy - MM - dd "
            placeholder="请选择添加时间"
            type="date"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </div>
        <div class="flex mt-3">
          <el-select
            v-model="listQuery.sale_status"
            clearable
            placeholder="请选择出售状态"
            style="width: 17%"
          >
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>

          <el-input
            v-model="listQuery.gift_price"
            class="ml-4"
            clearable
            placeholder="请输入价格"
            style="width: 17%"
          ></el-input>
          <el-input
            v-model="listQuery.gift_name"
            class="ml-4"
            clearable
            placeholder="请输入礼物名称"
            style="width: 17%"
          ></el-input>

          <div class="ml-4 flex items-center" style="width: 17%">
            <i
              class="el-icon-search p-1 text-white text-2xl bg-green-500 cursor-pointer"
              @click="getList"
            ></i>
            <i
              class="el-icon-refresh p-1 ml-3 text-white text-2xl bg-red-500 cursor-pointer"
              @click="resetClick"
            ></i>
          </div>
        </div>
      </div>

      <el-table :data="data" border @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column label="序号" prop="id" width="150px"></el-table-column>
        <el-table-column label="礼物名称" prop="name"></el-table-column>
        <el-table-column
          label="关系类别"
          prop="relation_type_name"
        ></el-table-column>
        <el-table-column
          label="关系名称"
          prop="relation_name"
        ></el-table-column>
        <el-table-column label="价格" prop="price"></el-table-column>
        <el-table-column
          label="奖池类别"
          prop="prize_pool_name"
        ></el-table-column>

        <el-table-column label="动态效果图" prop="special">
          <template slot-scope="scope">
            <div v-if="/.mp4$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <video
                  :src="scope.row.special"
                  controls
                  style="max-width: 200px"
                ></video>
                <video
                  slot="reference"
                  :src="scope.row.special"
                  autoplay
                  loop
                  muted
                  style="width: 50px"
                ></video>
              </el-popover>
            </div>
            <div v-else-if="/.webp$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <img
                  :src="scope.row.special"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.special"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </div>
            <div v-else-if="/.svga$/.test(scope.row.special)">
              <el-popover max-width="220" placement="right" trigger="hover">
                <!-- <svga :src="scope.row.special" :options="options"> -->
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="展示图片" prop="picture">
          <template slot-scope="{ row }">
            <el-popover max-width="420" placement="right" trigger="hover">
              <img
                :src="row.picture"
                alt=""
                style="max-width: 200px; max-height: 200px"
              />
              <img
                slot="reference"
                :src="row.picture"
                alt=""
                style="width: 50px"
              />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="出售状态" prop="sold">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.sold === 1" type="success">上架</el-tag>
            <el-tag v-else type="danger">下架</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="created_at"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              icon="el-icon-edit"
              plain
              size="mini"
              type="primary"
              @click="deBounceWrap(handleEdit, scope.row)"
            >编辑
            </el-button
            >
            <!-- <el-button
              type="danger"
              plain
              size="mini"
              icon="el-icon-delete"
              @click="deBounceWrap(handleDel, scope.row)"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <cus-pagination
        :limit.sync="listQuery.page_size"
        :page.sync="listQuery.page"
        :total="total"
        @pagination="getList"
      />
    </el-card>

    <el-dialog
      :before-close="handleClose"
      :close-on-click-modal="false"
      :title="titleOptions[title]"
      :visible.sync="dialogVisible"
      width="40%"
      @close="handleClear"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- <el-form-item prop="category_id" label="分类" label-width="120px">
          <el-cascader
            :change-on-select="true"
            :options="options"
            v-model="selectedOptions"
            :props="defaultParams"
            :clearable="true"
            @change="handleCascader"
          ></el-cascader>
        </el-form-item> -->
        <el-form-item label="礼物名称" label-width="120px" prop="gift_name">
          <el-input
            v-model="form.gift_name"
            clearable
            placeholder="请输入礼物名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="选择关系类别" prop="relation_type">
          <el-select
            v-model="form.relation_type"
            clearable
            placeholder="请选择关系类别"
          >
            <el-option
              v-for="item in styleLabelOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              clearable
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!expandArr.includes(form.relation_type)"
          label="关系名称"
          label-width="120px"
          prop="relation_name"
        >
          <el-input
            v-model="form.relation_name"
            clearable
            placeholder="请输入关系名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="礼物介绍" label-width="120px" prop="gift_desc">
          <el-input
            v-model="form.gift_desc"
            clearable
            maxlength="30"
            placeholder="请输入礼物介绍"
            show-word-limit
            type="textarea"
          ></el-input>
        </el-form-item>

        <el-form-item label="图片" label-width="120px" prop="picture">
          <el-upload
            :before-upload="handleBeforeUploadPicture"

            :http-request="customizeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img v-if="form.picture" :src="form.picture" class="avatar"/>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item
          v-if="!expandArr.includes(form.relation_type)"
          label="动效"
          prop="special"
        >
          <el-upload
            ref="upload"
            :auto-upload="true"
            :before-upload="handleBeforeUploadSpecial"
            :file-list="specialList"

            :http-request="customizeUpload"
            :on-change="handleChangePic"
            :on-remove="handleSpecialFlagBigRemove"
            :on-success="handleSpecialFlagBigSuccess"
            action=""
            class="upload-demo"
            list-type="text"
          >
            <el-button slot="trigger" size="small" type="primary"
            >上传特效
            </el-button
            >
          </el-upload>
        </el-form-item>
        <el-form-item label="礼物价格" label-width="120px" prop="gift_price">
          <el-input-number
            v-model.trim="form.gift_price"
            clearable
            placeholder="请输入礼物价格"
            type="number"
          ></el-input-number>
        </el-form-item>
        <el-form-item
          v-if="!expandArr.includes(form.relation_type)"
          label="人脉等级"
          prop="connect_level"
        >
          <el-select v-model="form.connect_level" clearable>
            <el-option :value="1" label="低"></el-option>
            <el-option :value="2" label="中"></el-option>
            <el-option :value="3" label="高"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="!expandArr.includes(form.relation_type)"
          label="关联奖池"
          prop="prize_pool_id"
        >
          <el-select
            v-model="form.prize_pool_id"
            clearable
            placeholder="请选择关联奖池"
          >
            <el-option :value="0" label="无奖池"></el-option>
            <el-option
              v-for="item in prizepoolAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              clearable
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="出售状态" prop="sale_status">
          <el-radio v-model="form.sale_status" :label="1">上架</el-radio>
          <el-radio v-model="form.sale_status" :label="0">下架</el-radio>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button plain type="primary" @click="handleClose">返回</el-button>
        <el-button type="primary" @click="deBounceWrap(handleSumbit, 'form')"
        >提交
        </el-button
        >
      </div>
    </el-dialog>

    <!-- 删除弹框
    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""
        ><em style="font-style: normal; color: red">删除后不可恢复</em
        >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog> -->
  </div>
</template>

<script>


import { cupidAdd, cupidEdit, cupidPropList, giftDetail, giftType, prizePool } from '@/api/contactKeepsake/contactKeep'

export default {
  data() {
    return {

      specialList: [],
      data: [],
      styleLabelOptions: [],
      prizepoolAll: [],
      /* 扩展的数组 */
      expandArr: [23, 24],
      listQuery: {
        relation_type: null,
        gift_name: undefined,
        gift_price: undefined,
        sale_status: null,
        add_time: undefined,
        page: 1,
        page_size: 10
      },
      total: 0,
      titleOptions: {
        add: '新增',
        edit: '编辑'
      },
      title: 'add',
      rowData: {},
      options: [],
      selectedOptions: [],
      defaultParams: {
        label: 'title',
        value: 'id',
        children: 'children'
      },
      form: {
        gift_name: undefined,
        relation_type: undefined,
        relation_name: undefined,
        connect_level: undefined,
        gift_desc: undefined,
        picture: undefined,
        special: undefined,
        gift_price: undefined,
        prize_pool_id: undefined,
        sale_status: undefined,
        prize_pool_name: undefined
        // category_id: undefined
      },
      rules: {
        gift_name: [
          { required: true, message: '请输入礼物名称', trigger: 'blur' }
        ],
        relation_type: [
          { required: true, message: '请选择关系类别', trigger: 'change' }
        ],
        relation_name: [
          { required: true, message: '请输入关系名称', trigger: 'blur' }
        ],
        gift_price: [
          { required: true, message: '请输入礼物价格', trigger: 'blur' }
        ],
        sale_status: [
          { required: true, message: '请选择出售状态', trigger: 'change' }
        ],
        picture: [
          { required: true, message: '请选择上传图片', trigger: 'change' }
        ],
        special: [
          { required: true, message: '请选择上传特效', trigger: 'change' }
        ],
        connect_level: [
          { required: true, message: '请选择人脉等级', trigger: 'change' }
        ],
        prize_pool_id: [
          { required: true, message: '请选择关联奖池', trigger: 'change' }
        ],
        category_id: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ]
      },
      dialogVisible: false,
      //删除
      deleteDialogVisible: false,
      //勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getList()
    this.getGiftType()
    this.getAllPool()
    // this.getGiftCategory();
  },
  methods: {
    //列表
    getList() {
      cupidPropList(this.listQuery).then(res => {
        this.data = res.data.data
        this.total = res.data.total
      })
    },
    //获取人脉关系类型
    getGiftType() {
      giftType({ op_type_category: 4 }).then(res => {
        this.styleLabelOptions = res.data
      })
    },
    //获取所有人脉奖池
    getAllPool() {
      prizePool().then(res => {
        this.prizepoolAll = res.data
      })
    },
    //获取所有礼物分类
    // getGiftCategory() {
    //   giftCategory().then(res => {
    //     this.options = this.getTreeData(res.data);
    //   });
    // },
    // 递归方法
    getTreeData(data) {
      // 循环遍历json数据
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children)
        }
      }
      return data
    },

    handleSuccess() {
      this.form.picture = this.ossLastImgUrl
    },
    handleBeforeUploadPicture(file) {
      const isPic =
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp'

      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPic) {
        this.$message.error('请上传图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPic && isLt2M
    },

    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },
    handleBeforeUploadSpecial(file) {
      const isMp4 = file.type === 'video/mp4'
      if (!isMp4) {
        this.$message.error('上传特效只能为 MP4 格式!')
      }
      return isMp4
    },
    handleSpecialFlagBigRemove(res) {
      this.form.special = undefined
      this.specialList = []
    },
    handleSpecialFlagBigSuccess() {
      this.form.special = this.ossLastImgUrl
      this.specialList = [{ name: this.ossLastImgUrl }]
    },
    //重置
    resetClick() {
      this.listQuery = {
        relation_type: null,
        gift_name: undefined,
        gift_price: undefined,
        sale_status: null,
        add_time: undefined,
        page: 1,
        page_size: 10
      }

      this.getList()
    },
    //新增
    handleAdd() {
      this.title = 'add'
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.title = 'edit'
      this.specialList = []
      this.rowData = row

      giftDetail({ id: row.id }).then(res => {
        this.form.gift_name = res.data.name
        this.form.picture = res.data.picture
        this.form.relation_type = res.data.op_type
        this.form.relation_name = res.data.ext_field.relation_name
        this.form.connect_level = res.data.ext_field.connect_level
        this.form.gift_price = res.data.price
        this.form.prize_pool_id = res.data.prize_pool_group_id
        this.form.sale_status = res.data.sold
        this.form.gift_desc = res.data.desc
        // this.form.category_id = res.data.category_id;
        // if (res.data.category_id) {
        //   this.selectedOptions = res.data.category_id;
        // }
      })
      this.form.special = this.rowData.special
      if (row.special) {
        this.specialList = [{ name: row.special }]
      }

      this.dialogVisible = true
    },
    handleSumbit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.title === 'add') {
            let data = {
              gift_name: this.form.gift_name,
              relation_type: this.form.relation_type,
              relation_name: this.form.relation_name,
              connect_level: this.form.connect_level,
              gift_desc: this.form.gift_desc,
              picture: this.form.picture,
              special: this.form.special,
              gift_price: this.form.gift_price,
              prize_pool_id: this.form.prize_pool_id,
              sale_status: this.form.sale_status
              // category_id: this.form.category_id
            }

            cupidAdd(data).then(res => {
              if (res.code === 200) {
                this.$message.success('提交成功')
                this.getList()
                this.dialogVisible = false
              } else {
              }
            })
          }
          if (this.title === 'edit') {
            let data1 = {
              id: this.rowData.id,
              gift_name: this.form.gift_name,
              relation_type: this.form.relation_type,
              relation_name: this.form.relation_name,
              connect_level: this.form.connect_level,
              gift_desc: this.form.gift_desc,
              picture: this.form.picture,
              special: this.form.special,
              gift_price: this.form.gift_price,
              prize_pool_id: this.form.prize_pool_id,
              sale_status: this.form.sale_status
              // category_id: this.form.category_id
            }

            cupidEdit(data1).then(res => {
              if (res.code === 200) {
                this.$message.success('编辑成功')
                this.getList()
                this.dialogVisible = false
              }
            })
          }
        } else {

          return false
        }
      })
    },
    //清空表单
    handleClose() {
      this.dialogVisible = false
    },
    handleClear() {
      this.$refs['form'].resetFields()
      this.form = {
        gift_name: undefined,
        relation_type: undefined,
        relation_name: undefined,
        connect_level: undefined,
        gift_desc: undefined,
        picture: undefined,
        special: undefined,
        gift_price: undefined,
        prize_pool_id: undefined,
        sale_status: undefined
      }
      this.specialList = []
      this.selectedOptions = []
    },

    handleSelectionChange(val) {
      this.multipleSelection = val
    }

    //  handleDelAll(){
    //     if (this.multipleSelection.length) {
    //     /* 存在勾选数据 */ const ids = this.multipleSelection.reduce(
    //       (pre, currRow) => {
    //         pre += `${currRow.id},`;
    //         return pre;
    //       },
    //       ""
    //     );
    //     cupidDel({ ids })
    //       .then(() => this.$message.success("删除成功！"))
    //       .catch(console.error)
    //       .finally(() => /* 刷新数据 */ {
    //         this.multipleSelection = [];
    //         this.getList()
    //       });
    //   } /* 不存在勾选数据 */ else {
    //     this.$message.warning("请勾选要删除的数据！");
    //   }
    // },
    //删除
    // handleDel(row) {
    //   this.dataIds = { ids: `${row.id}` };
    //   this.deleteDialogVisible = true;
    // },
    // 确定删除
    // confirmDelete() {
    //   cupidDel(this.dataIds).then((response) => {
    //     if (response.code === 200) {
    //       this.getList();
    //       this.deleteDialogVisible = false;
    //       this.$notify({
    //         type: "success",
    //         message: "操作成功",
    //       });
    //     }
    //   });
    // },
  }
}
</script>
<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}

/deep/ .el-upload-list__item {
  transition : none !important;
}

/deep/ .el-upload-list--picture {
  max-height : 103px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list--text {
  max-height : 100px !important;
  overflow   : hidden;
}

/deep/ .el-upload-list__item-name {
  white-space : normal !important;
}

/deep/ .el-cascader-menu {
  height : 0px;
}
</style>
